package com.sh.personnel.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sh.personnel.config.redis.RedisConstant;
import com.sh.personnel.domain.ITbUser;
import com.sh.personnel.mapper.IUserMapper;
import com.sh.personnel.security.ISecurityUser;
import com.sh.personnel.service.IUserService;
import com.sh.personnel.util.*;
import com.sh.personnel.vo.RegisterVo;
import com.sh.personnel.vo.dto.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 用户业务类
 * @author 林思浩
 * @date 2020/02/27 16:03
 */
@Service
public class IUserServiceImpl implements IUserService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IUserMapper userMapper;
    
    /**
     * 登录用户
     * @param username
     * @param password
     * @return
     */
    @Override
    public String login(String username, String password) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authentication = authenticationManager.authenticate(authenticationToken); //用户验证，由security帮我们去验证用户名和密码（接下来会走到loadUserByUsername(username)）
        SecurityContextHolder.getContext().setAuthentication(authentication);
        ISecurityUser securityUser = (ISecurityUser) authentication.getPrincipal();
        String token = JwtUtil.generateToken(securityUser);
        return token;
    }

    /**
     * 注册用户（用户自己创建，不需要默认密码）
     * @param register
     * @return
     */
    @Override
    @Transactional
    public Boolean register(RegisterVo register) {
        ITbUser user = new ITbUser();
        user.setName(register.getName())
                .setPassword(PwUtil.encrypt(register.getPassword()))
                .setEmail(register.getEmail())
                .setCreatetime(TimeUtil.currentMillis())
                .setAvatar(AvatarUtil.DEFAULT_AVATAR)
                .setUsername(getUsername())
                .setId(RandomUtil.generateUuid());
        int result = userMapper.insertUser(user);
        return result>0 ? true : false;
    }


    /**/

    /**
     * 分页获取用户列表
     * @param page
     * @param key
     * @param deptId
     * @param state
     * @return
     */
    @Override
    public PageInfo<UserDto> getUserList(Integer page, String key, String deptId, Integer state) {
        PageHelper.startPage(page, 9);
        List<UserDto> list = userMapper.findUserList(key, deptId, state);
        return new PageInfo<>(list);
    }

    /**
     * 新增用户(由管理员创建，密码自动生成)
     * @param user
     * @return
     */
    @Override
    public boolean insertUser(ITbUser user) {
        int result = 0;
        String username = getUsername();
        String id = RandomUtil.generateUuid();
        user.setId(id)
                .setUsername(username)
                .setPassword(PwUtil.encrypt(username.substring(username.length()-6, username.length())))
                .setAvatar(AvatarUtil.DEFAULT_AVATAR)
                .setCreatetime(TimeUtil.currentMillis());
        if(user.getDeptIds() != null) user.setDepartmentid(user.getDeptIds().get(0));
        if(userMapper.insertUser(user) > 0) {
            if(user.getRoleIds()!=null) {
                result = userMapper.insertUserRoleByUserId(user.getRoleIds(), id);
            }
        }
        return result>0 ? true : false;
    }

    /**
     * 获取指定用户编辑信息
     * @param id
     * @return
     */
    @Override
    public ITbUser getUserById(String id) {
        ITbUser user = userMapper.findUserById(id);
        List<Integer> departmentId = new ArrayList<>();
        departmentId.add(user.getDepartmentid());
        user.setRoleIds(userMapper.findRoleIdsByUserId(id))
            .setDeptIds(departmentId);
        return user;
    }

    /**
     * 更新指定用户编辑信息
     * @param user
     * @return
     */
    @Override
    @Transactional
    public boolean updateUserById(ITbUser user) {
        int result = 0;
        if(user.getDeptIds() != null) user.setDepartmentid(user.getDeptIds().get(0));
        if(userMapper.updateUserById(user) > 0) {
            userMapper.deleteRoleIdByUserId(user.getId());
            result = userMapper.insertUserRoleByUserId(user.getRoleIds(), user.getId());
        }
        return result>0 ? true : false;
    }

    /**
     * 删除指定用户
     * @param id
     * @return
     */
    @Override
    public boolean deleteUserById(String id) {
        int result = userMapper.deleteUserById(id);
        return result>0 ? true : false;
    }


    /**
     * 内部方法/获取流水工号
     * @return
     */
    private String getUsername() {
        String username = String.valueOf(redisTemplate.opsForValue().increment(RedisConstant.INIT_USERNAME));
        return username;
    }
}
